package rhc.singleNodeSpider.spiderManage.impl;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import rhc.singleNodeSpider.BasicComponent;
import rhc.singleNodeSpider.spider.SingleNodeSpider;
import rhc.singleNodeSpider.spider.SpiderBuilder;
import rhc.singleNodeSpider.spiderManage.SpiderManage;
import rhc.spider.setting.Setting;

/**爬虫管理实现
 * @author lenovo
 *
 */
public class SpiderManageImpl extends BasicComponent implements SpiderManage {

	/**
	 * 任务id-单/节点爬虫
	 */
	Map<String,SingleNodeSpider> taskId_singleNodeSpider=new HashMap<String,SingleNodeSpider>();
	
	@Override
	public List<String> getRunningTaskId() throws Exception {
		return new LinkedList<String>(taskId_singleNodeSpider.keySet());
	}

	@Override
	public void createTask(String taskId) throws Exception {
		Setting setting=this.getTaskSetting(taskId);
		SingleNodeSpider singleNodeSpider=SpiderBuilder.create(taskId).build();
		this.addSingleNodeSpider(taskId, singleNodeSpider);
	}

	@Override
	public void runTask(String taskId) throws Exception {
		SingleNodeSpider singleNodeSpider=this.getSingleNodeSpider(taskId);
		singleNodeSpider.run();
	}

	@Override
	public void stopTask(String taskId) throws Exception {
		SingleNodeSpider singleNodeSpider=this.getSingleNodeSpider(taskId);
		singleNodeSpider.stop();
	}

	@Override
	public void pauseTask(String taskId) throws Exception {
		SingleNodeSpider singleNodeSpider=this.getSingleNodeSpider(taskId);
		singleNodeSpider.stop();
	}

	@Override
	public void regainTask(String taskId) throws Exception {
		SingleNodeSpider singleNodeSpider=this.getSingleNodeSpider(taskId);
		singleNodeSpider.run();
	}
	
	@Override
	public boolean containsTask(String taskId) throws Exception {
		return taskId_singleNodeSpider.containsKey(taskId);
	}
	
	/**获取任务配置
	 * @param taskId
	 * @return
	 */
	private Setting getTaskSetting(String taskId){
		return null;
	}
	
	/**增加一个单节点爬虫
	 * @param taskId
	 * @param singleNodeSpider
	 */
	private void addSingleNodeSpider(String taskId,SingleNodeSpider singleNodeSpider){
		taskId_singleNodeSpider.put(taskId, singleNodeSpider);
	}
	
	/**移除一个单节点爬虫
	 * @param taskId
	 * @return
	 */
	private SingleNodeSpider removeSingleNodeSpider(String taskId){
		return taskId_singleNodeSpider.remove(taskId);
	}
	
	/**根据任务id获取单节点爬虫
	 * @param taskId
	 * @return
	 */
	private SingleNodeSpider getSingleNodeSpider(String taskId){
		SingleNodeSpider singleNodeSpider = taskId_singleNodeSpider.get(taskId);
		if(null == singleNodeSpider){
			throw new IllegalArgumentException(taskId+" 不存在");
		}
		return singleNodeSpider;
	}

}
